
using UnityEngine;
using System.Collections;

public class InfiniteBounce : MonoBehaviour
{
    private float bounceHeight = 30f; // 弹跳高度
    private float bounceDuration = 0.3f; // 单次弹跳持续时间
    private float intervalDuration = 1f; // 弹跳间隔时间
    private int bounceCount = 3; // 每次触发时的弹跳次数
    public bool startOnAwake = false; // 是否在 Awake 时自动开始弹跳

    private Vector3 startPosition;
    private Coroutine bounceCoroutine;
    private bool isBouncing = false;

    private void Awake()
    {
        startPosition = transform.position;
        if (startOnAwake)
        {
            StartBouncing();
        }
    }

    // 开始弹跳
    public void StartBouncing()
    {
        if (!isBouncing)
        {
            isBouncing = true;
            bounceCoroutine = StartCoroutine(BounceCoroutine());
        }
    }

    // 停止弹跳
    public void StopBouncing()
    {
        if (isBouncing)
        {
            isBouncing = false;
            if (bounceCoroutine != null)
            {
                StopCoroutine(bounceCoroutine);
            }
            transform.position = startPosition;
        }
    }

    private IEnumerator BounceCoroutine()
    {
        while (isBouncing)
        {
            for (int i = 0; i < bounceCount; i++)
            {
                yield return StartCoroutine(SingleBounce());
            }
            yield return new WaitForSeconds(intervalDuration);
        }
    }

    private IEnumerator SingleBounce()
    {
        float elapsedTime = 0f;
        Vector3 initialPosition = transform.position;

        while (elapsedTime < bounceDuration)
        {
            elapsedTime += Time.deltaTime;
            float progress = elapsedTime / bounceDuration;
            float height = Mathf.Sin(progress * Mathf.PI) * bounceHeight;
            transform.position = initialPosition + Vector3.up * height;
            yield return null;
        }

        transform.position = initialPosition;
    }
}